package com.kang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kang.bean.Play;
import com.kang.bean.PlayPic;
import com.kang.commons.Result;
import com.kang.commons.util.QiniuUtil;
import com.kang.mapper.PlayMapper;
import com.kang.service.PlayService;
import com.kang.vo.PlayVo;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

/**
 * @program: service
 * @description: 游乐设施实现类
 * @author: K.faWu
 * @create: 2022-03-29 10:12
 **/
@Service
public class PlayServiceImpl extends ServiceImpl<PlayMapper, Play> implements PlayService {
    private final PlayMapper playMapper;
    private final QiniuUtil qiniuUtil;

    public PlayServiceImpl(PlayMapper playMapper, QiniuUtil qiniuUtil) {
        this.playMapper = playMapper;
        this.qiniuUtil = qiniuUtil;
    }

    @Override
    public void addPlay(Play play) {
        playMapper.addPlay(play);
    }

    @Override
    public PageInfo<PlayVo> queryList(Pageable page, PlayVo playVo) {
        //设置分页条件
        PageHelper.startPage(page.getPageNumber(),page.getPageSize());
        List<PlayVo> playList = playMapper.queryList(playVo);

        return new PageInfo<PlayVo>(playList);
    }

    @Override
    public void updatePlay(Play play) {
        playMapper.updatePlay(play);
    }

    @Override
    public String addPic(MultipartFile file) {
        //文件名
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        int i = originalFilename.lastIndexOf(".");
        String endName = originalFilename.substring(i);
        endName = endName.toLowerCase();
        //判断是否是指定类
        List<String> fileType = Arrays.asList(".gif", ".jpg", ".jfif", ".ico", ".png", ".bmp", ".svg");
        if (!fileType.contains(endName)) {
            Result.error("文件类型错误");
        }
        try {
            String path = qiniuUtil.setUploadManager(file.getInputStream());
            if (path == null){
                Result.error("输入的字符不能为空！");
            }

            //获取文件名
            /* 路径保存到数据库中 */
            PlayPic pic = new PlayPic();
            pic.setRealname(originalFilename);
            pic.setSavepath(path);
            pic.setCover(0);
            pic.setUploadtime(new Timestamp(System.currentTimeMillis()));

            return path;
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("文件上传失败");
        }
        return null;
    }
}
